from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from views.third_party_auth import third_party_auth
from views.login import login as auth_router
from api_simple import include_api_routes
from contextlib import asynccontextmanager
from tortoise import Tortoise

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    try:
        # 启动时初始化数据库
        await Tortoise.init(
            db_url='mysql://root:123456@39.107.155.107:3307/paopao',
            modules={'models': ['models']}
        )
        await Tortoise.generate_schemas()
        print("✅ 数据库初始化完成")
    except Exception as e:
        print(f"⚠️ 数据库初始化失败，使用内存模式: {e}")
        # 如果数据库连接失败，初始化内存数据库进行演示
        await Tortoise.init(
            db_url='sqlite://:memory:',
            modules={'models': ['models']}
        )
        await Tortoise.generate_schemas()
        print("✅ 内存数据库初始化完成（演示模式）")

    yield

    # 关闭时关闭数据库连接
    await Tortoise.close_connections()
    print("✅ 数据库连接已关闭")

app = FastAPI(
    title="泡泡旅游API",
    description="集成了生成器、迭代器、装饰器、深浅拷贝、静态方法等Python高级特性",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 所有客户端
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含API路由
app.include_router(third_party_auth, prefix='/api', tags=['第三方登录'])
app.include_router(auth_router, prefix='/auth', tags=['用户认证'])
include_api_routes(app)

@app.get("/")
async def root():
    """根路径 - API信息"""
    return {
        "message": "欢迎使用泡泡旅游API",
        "description": "集成了生成器、迭代器、装饰器、深浅拷贝、静态方法等Python高级特性",
        "features": [
            "生成器(Generator) - 高效处理大量数据",
            "迭代器(Iterator) - 内存友好的数据遍历",
            "装饰器(Decorator) - 性能监控、缓存、认证",
            "深浅拷贝 - 数据安全复制",
            "静态方法(Static Methods) - 工具类方法",
            "钉钉第三方登录 - 完整的OAuth登录和数据存储"
        ],
        "apis": {
            "用户认证": [
                "POST /auth/login - 用户登录",
                "POST /auth/register - 用户注册",
                "GET /auth/profile - 获取用户资料",
                "POST /auth/refresh-token - 刷新token"
            ],
            "卡片管理": [
                "GET /api/v1/cards - 卡片列表(分页、过滤、缓存)",
                "GET /api/v1/cards/{id} - 单个卡片(深浅拷贝演示)",
                "GET /api/v1/cards/generator-demo - 生成器演示",
                "GET /api/v1/cards/batch-demo - 批量处理演示",
                "GET /api/v1/cards/cache-demo - 缓存机制演示",
                "GET /api/v1/cards/static-methods - 静态方法演示"
            ],
            "第三方登录": [
                "GET /api/auth/dingtalk/login - 钉钉登录",
                "GET /api/auth/gitee/login - Gitee登录",
                "GET /api/auth/dingtalk/callback - 钉钉回调",
                "GET /api/auth/database/stats - 数据库统计"
            ]
        },
        "frontend_demo": {
            "vue_component": "http://localhost:5173/src/components/ApiDemo.vue",
            "demo_page": "http://localhost:5173/#/api-demo",
            "description": "前端Vue组件演示所有Python高级特性"
        },
        "documentation": {
            "swagger_ui": "/docs",
            "redoc": "/redoc",
            "openapi_json": "/openapi.json"
        },
        "github": "https://github.com/your-repo/python-features-demo"
    }


if __name__ == '__main__':
    print("启动泡泡旅游API服务器...")
    print("访问 http://127.0.0.1:8000/docs 查看API文档")
    uvicorn.run("main_fixed:app", host="127.0.0.1", port=8000, reload=True)
